import request, { extend } from 'umi-request';
import { message } from 'antd';
import { SingleUserType, FormValues } from './data.d';

const errorHandler = function(error: any) {
  if (error.response) {
    if (error.response.status > 400) {
      message.error(error.data.message ? error.data.message : error.data);
    }
  } else {
    // 请求已经发送，但是没有回复
    message.error('Network Error .');
  }

  // 持续抛出错误
  throw error; // If throw. The error will continue to be thrown.

  // return {some: 'data'}; If return, return the value as a return. If you don't write it is equivalent to return undefined, you can judge whether the response has a value when processing the result.
  // return {some: 'data'};
};

const extendRequest = extend({ errorHandler });

export const getRemoteList = async ({ page, per_page }) => {
  return extendRequest(`/api/users?page=${page}&&per_page=${per_page}`, {
    method: 'get',
  })
    .then(function(response) {
      console.log(response);
      return response;
    })
    .catch(function(error) {
      console.log(error);
      return false;
    });
};

export const editRecord = async ({
  id,
  values,
}: {
  id: number;
  values: FormValues;
}) => {
  return extendRequest(`/api/users/${id}`, {
    method: 'put',
    data: values,
  })
    .then(function(response) {
      return true;
    })
    .catch(function(error) {
      return false;
    });
};

// 删除
export const deleteRecord = async ({ id }: { id: number }) => {
  return extendRequest(`/api/users/${id}`, {
    method: 'delete',
  })
    .then(function(response) {
      return true;
    })
    .catch(function(error) {
      return false;
    });
};

// 添加
export const addRecord = async ({ values }: { values: FormValues }) => {
  return extendRequest('/api/users', {
    method: 'post',
    data: values,
  })
    .then(function(response) {
      return true;
    })
    .catch(function(error) {
      return false;
    });
};
